<?php
/**
 * 这是个PDO示例，它不需要手动抛出错误
 * User: ford
 * Date: 15-6-25
 * Time: 下午3:58
 */
if(argc != 3) {
	die("USAGE:php pdocreate.php <table_name> <file_name>\n");
}

$table_name = $argv[1];
$file_name = $argv[2];
$row_num = 0;
function create_insert_stmt($table, $ncols) {
	$stmt = "INSERT INTO $table VALUES(";
	foreach(range(1, $ncols) as $i) {
		$stmt .= "?,";
	}

	$stmt = preg_replace("/,$/", ')', $stmt);

	return $stmt;
}

try{
	$db = new PDO('mysql:host=localhost;dbname=scott', 'root', 'al8840dd');
	$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);	//定义PDO出错时抛出PDOException类对象
	$res = $db->prepare("SELECT * FROM $table_name");
	$res->execute();

	$ncols = $res->columnCount();
	$ins = create_insert_stmt($table_name, $ncols);
	$res = $db->prepare($ins);

	$fp = new SplFileObject($file_name, 'r');
	$db->beginTransaction();
	while($row = $fp->fgetcsv()) {
		if(strlen(implode('', $row)) == 0) {
			continue;
		}
		$res->execute($row);
		$row_num++;
	}
	$db->commit();	//PDO不能关闭自动提交模式，它可以这样显示提交启动事务
	echo "$row_num rows inserted into $table_name.\n";
}
catch (Exception $e) {
	echo "Exceptoin:\n";
	die($e->getMessage() . "\n");
}